const express = require('express')
const boom = require('boom')
const authRouter = require('./auth')
const userRouter = require('./user')
const bookRouter = require('./book')
const shelfsRouter = require('./shelf')
const markRouter = require('./mark')
const noteRouter = require('./note')
const readRouter = require('./read')

// 注册路由
const router = express.Router()

router.get('/', function (req, res) {
  res.send('欢迎使用芒果阅读管理后台')
})

router.use('/', authRouter)
router.use('/', userRouter)
router.use('/', bookRouter)
router.use('/', shelfsRouter)
router.use('/', markRouter)
router.use('/', noteRouter)
router.use('/', readRouter)

/**
 * 集中处理404请求的中间件
 * 注意：该中间件必须放在正常处理流程之后
 * 否则，会拦截正常请求
 */
router.use((req, res, next) => {
  next(boom.notFound('接口不存在'))
})

/**
 * 自定义路由异常处理中间件
 * 注意两点：
 * 第一，方法的参数不能减少
 * 第二，方法的必须放在路由最后
 */
router.use((err, req, res, next) => {
  const statusCode = (err.output && err.output.statusCode) || 500;
  const errorMsg = (err.output && err.output.payload && err.output.payload.message) || err.message
  console.log(statusCode, errorMsg)
  res.status(statusCode).json({
    status: statusCode,
    error: errorMsg
  })
})

module.exports = router
